package com.suzhouhe.util.config;

import com.suzhouhe.util.interceptor.ControllerLogInterceptor;
import com.suzhouhe.util.interceptor.ResponseResultInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 拦截器配置
 *
 * @author suzhouhe
 * @date 2020-11-04 15:36
 **/
@Configuration
public class UtilInterceptorConfig implements WebMvcConfigurer {

    private final ResponseResultInterceptor responseResultInterceptor;

    private final ControllerLogInterceptor controllerLogInterceptor;

    /* 拦截器配置处理是否需要做结果解析  */

    @Autowired
    public UtilInterceptorConfig(ResponseResultInterceptor responseResultInterceptor, ControllerLogInterceptor controllerLogInterceptor) {
        this.responseResultInterceptor = responseResultInterceptor;
        this.controllerLogInterceptor = controllerLogInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加拦截器，配置拦截地址
        registry.addInterceptor(responseResultInterceptor).addPathPatterns("/**");
        registry.addInterceptor(controllerLogInterceptor).addPathPatterns("/**");
    }

    /* 返回中文乱码解决  */

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        //解决返回值中文乱码
        return new StringHttpMessageConverter(StandardCharsets.UTF_8);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        WebMvcConfigurer.super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }

}
